package com.eqdd.yiqidian.ui.yiqiyue.fragment;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.YueHotArticleFragmentCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows;
import com.eqdd.yiqidian.bean.rebuild.YueArticleListBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.mine.maker.OwnerMakerSpaceActivity;
import com.eqdd.yiqidian.ui.mine.space.OwnerComSpaceActivity;
import com.eqdd.yiqidian.ui.yiqiyue.ArticleInfoActivity;
import com.eqdd.yiqidian.ui.yiqiyue.YueLabelListActivity;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.rong.imkit.utils.RongDateUtils;

/**
 * @author吕志豪 .
 * @date 17-12-6  下午2:33.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class YueFragment extends BaseFragment {
    YueHotArticleFragmentCustom dataBinding;
    private SlimAdapterEx<YueArticleListBean> slimAdapterEx;
    private int pageNum = 0;
    private String url;
    private Bundle bundle;
    private String para = "";
    private MVCCoolHelper<List<YueArticleListBean>> mvcHelper;
    private String label;
    private String guid;

    @Override
    protected void setView() {
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void initData() {
        if (slimAdapterEx == null) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_80, new SlimInjector<YueArticleListBean>() {
                @Override
                public void onInject(YueArticleListBean data, IViewInjector injector) {
                    try {
                        injector.image(R.id.iv_head, data.getIphoto())
                                .text(R.id.stv_name, data.getUpname())
                                .text(R.id.tv_title, data.getTitle())
                                .gone(R.id.iv_option)
                                .gone(R.id.rl_bg)
                                .text(R.id.tv_depart, RongDateUtils.getConversationFormatDate(sf.parse(data.getCreateTime()).getTime(), getActivity()))
                                .image(R.id.iv_img, data.getImage())
                                .text(R.id.tv_content, data.getContent())
                                .visibility(R.id.iv_img, TextUtils.isEmpty(data.getImage().trim()) ? View.GONE : View.VISIBLE)
                                .text(R.id.tv_source, data.getSource())
                                .text(R.id.stv_msg, data.getCommentCount() + "评论")
                                .text(R.id.stv_look, data.getBrowseCount() + "阅读")
                                .text(R.id.stv_support, data.getZanCount() + "点赞")
                                .clicked(R.id.iv_head, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString(Config.GUID, data.getUserGuid());
                                        bundle.putString("avatar", data.getImage());
                                        bundle.putString("name", data.getUpname());
                                        startActivity(OwnerMakerSpaceActivity.class, bundle);
                                    }
                                })
                                .clicked(R.id.tv_source, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if ("企业空间".equals(data.getSource())) {
                                            Bundle bundle = new Bundle();
                                            bundle.putInt(Config.COMPANY_ID,data.getCompanyId());
                                            startActivity(OwnerComSpaceActivity.class);
                                        } else if ("创客空间".equals(data.getSource())) {
                                            Bundle bundle = new Bundle();
                                            bundle.putString(Config.GUID, data.getUserGuid());
                                            bundle.putString("avatar", data.getImage());
                                            bundle.putString("name", data.getUpname());
                                            startActivity(OwnerMakerSpaceActivity.class, bundle);
                                        }
                                    }
                                })
                                .with(R.id.recyclerViewLabel, view -> {
                                    if (data.getLable() == null) {
                                        return;
                                    }
                                    RecyclerView recyclerViewLabel = (RecyclerView) view;
                                    List<String> stringList = new ArrayList<>();
                                    for (String s : data.getLable().split(",")) {
                                        if (!TextUtils.isEmpty(s)) {
                                            stringList.add(s);
                                        }
                                    }
                                    recyclerViewLabel.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
                                    SlimAdapterEx<String> slimAdapterExLabel = SlimAdapterEx.create().register(R.layout.list_item_74, new SlimInjector<String>() {
                                        @Override
                                        public void onInject(String data, IViewInjector injector) {
                                            injector.gone(R.id.iv_clear)
                                                    .text(R.id.tv_content, data);
                                        }
                                    }).attachTo(recyclerViewLabel).updateData(stringList);
                                    ItemClickSupport.addTo(recyclerViewLabel)
                                            .setOnItemClickListener((recyclerView, position, v) -> {
                                                Bundle bundle = new Bundle();
                                                bundle.putString(Config.LABEL, slimAdapterExLabel.getDataItem(position));
                                                startActivity(YueLabelListActivity.class, bundle);
                                            });
                                });
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
            ModelRx2DataSource<YueArticleListBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    pageNum = page == 1 ? 0 : pageNum;
                    return OkGo.<HttpResultRows<YueArticleListBean>>post(HttpConfig.BASE_URL + url)
                            .params("page", pageNum)
                            .params("userGuid", TextUtils.isEmpty(guid) ? AppConstent.user.getGuid() : guid)
                            .params("time", 7)
                            .params("type", "app")
                            .params("para", para)
                            .params("lable", label)
                            .converter(new JsonConverter<HttpResultRows<YueArticleListBean>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<>())
                            .flatMap(listResultBean -> {
                                pageNum = listResultBean.getItems().getPage();
                                if (listResultBean.getStatus() == 200) {
                                    return Flowable.just(listResultBean.getItems() == null ? new ArrayList<YueArticleListBean>() : listResultBean.getItems().getRows());
                                } else {
                                    ToastUtil.showShort(listResultBean.getMsg());
                                    return Flowable.just(new ArrayList<>());
                                }
                            });

                }
            });
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();
            ItemClickSupport.addTo(dataBinding.recyclerView)
                    .setOnItemClickListener((recyclerView, position, v) -> {

                        bundle = new Bundle();
                        bundle.putInt(Config.ID, slimAdapterEx.getDataItem(position).getId());
                        startActivity(ArticleInfoActivity.class, bundle);
                    });
        }
    }


    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        url = getArguments().getString(Config.URL);
        label = getArguments().getString(Config.LABEL);
        guid = getArguments().getString(Config.GUID);
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_yue_hot_article, null, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onClick(View v) {

    }

    public void search(CharSequence para) {
        this.para = para.toString();
        mvcHelper.refresh();
    }

    public void changeLabel(CharSequence label) {
        this.label = label.toString();
        mvcHelper.refresh();
    }


}
